package com.ving.test.mybatis02.binding;

import com.ving.test.mybatis.session.Configuration;
import com.ving.test.mybatis.util.DBUtil;
import com.ving.test.mybatis02.resultset.ResultSetHandler02;
import com.ving.test.mybatis02.session.Configuration02;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * Created by liuweijie on 2019-11-19.
 */
public class MapperProxy02 implements InvocationHandler {

    private Configuration02 configuration02;
    private Class zlass;

    public MapperProxy02(Configuration02 configuration02, Class zlass) {
        this.configuration02 = configuration02;
        this.zlass = zlass;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String key = method.getDeclaringClass().getName()+"."+method.getName();
        MapperMethod02 mapperMethod02 = (MapperMethod02) configuration02.getMapperRegister02().getMapperRegister().get(key);
        if(mapperMethod02!=null){
            String sql = mapperMethod02.getSql();
            String par = String.valueOf(args[0]);
           String newSql = String.format(sql,par);
            Connection con = DBUtil.getConnection();
            PreparedStatement re = con.prepareStatement(newSql);
            re.execute();
            return new ResultSetHandler02().handle(re,mapperMethod02);
        }
        return method.invoke(proxy,args);
    }
}
